<?php

namespace App\Http\Controllers\Admin;

use App\Handler\ImageHandler;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\WebConfig as WebConfigModel;

class WebConfig extends Controller
{
	use ImageHandler;
	/**
	 * 配置首页
	 * User: ihome
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function index()
    {
    	$site_info = WebConfigModel::all()->toArray();
		$site_info = array_column($site_info,'value','en_name');
		
		return view('admin.web_config.index',compact('site_info'));
    }

	/**
	 * 配置修改
	 * User: ihome
	 */
	public function store(Request $request,WebConfigModel $webConfigModel)
    {
		if(\request()->method() == 'POST'){
			$data = $request->except(['_token','thumb']);

			foreach ($data as $k => $v) {
				$insertData = [
					'en_name'=>$k,
					'value'=>$v,
				];
				$webConfigModel->fill($insertData);
				$webConfigModel->where('en_name',$k)->update($insertData);
			}

			//判断图片有没上传
			if($request->hasFile('thumb')){
				$uploadImg = $this->upLoadToAliOss('thumb','web_config/','conf_');
				if($uploadImg['status'] == 200){

					$config = WebConfigModel::query()->where(['en_name'=>'thumb'])->firstOrFail();
					$old_thumb = $config->value; //上传本地时，需要删除旧文件

					$config->update(['value'=>$uploadImg['path']]);
//				    @unlink(public_path() . '/' . $old_thumb);

					//删除阿里云上的文件
					$file_name =  $this->cutFileName($old_thumb);
					$this->delAliOssFile($file_name);
				}else{
					return back()->with('danger',$uploadImg['msg']);
				}
			}

			return back()->with('success','修改成功');
		}
    }
}
